<template>
  <div>
    <div>
      <el-form :inline="true">
        <div class="commontop">
          <div class="commontop-left">
            <el-input
              placeholder="请输入角色名称"
              v-model="pages.keyword"
              @change="INput"
              @clear="INput"
              @keyup.enter.native="goSearch()"
              clearable
              prefix-icon="el-icon-search"
            ></el-input>
            <el-button
              class="searchbgc"
              @click="goSearch"
              icon="iconfont icon-sousuo2"
              >搜索</el-button
            >
            <el-button
              v-show="xsyc === '1' ? true : false"
              icon="iconfont icon-tianjiaanjuanfengmian"
              @click="Addrole"
              >添加角色</el-button
            >
          </div>
        </div>
      </el-form>
      <el-dialog :visible.sync="drawerVisible" width="30%" class="tab">
        <el-form
          :model="roleForm"
          :rules="rules"
          ref="roleForm"
          label-width="88px"
          label-position="left"
        >
          <el-form-item prop="title" label="角色名">
            <el-input
              v-model="roleForm.title"
              placeholder="请输入角色名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="permissions" label="授权">
            <el-tree
              ref="tree"
              show-checkbox
              node-key="id"
              :data="data"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
          <div class="login-btn">
            <el-button @click="drawerVisible = false">取 消</el-button>
            <el-button type="primary" @click="getCheckedNodes('roleForm')"
              >保存</el-button
            >
          </div>
        </el-form>
      </el-dialog>

      <el-table
        v-loading="isLoading"
        element-loading-spinner="el-icon-loading"
        element-loading-text="玩命加载中"
        :data="tableData"
        ref="multipleSelection"
        :header-cell-style="{ backgroundColor: '#3963fd', color: '#fff' }"
        style="width: 100%; margin-top: 20px"
      >
        <template slot="empty">
          <img src="@/assets/imgs/暂未数据.png" alt style="margin-top: 104px" />
          <p style="margin-top: 15px; margin-bottom: 104px">暂未有数据</p>
        </template>
        <!-- <el-table-column type="selection"></el-table-column> -->
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="SwitchChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template
            slot-scope="scope"
            v-if="scope.row.is_edit == 0 ? false : true"
          >
            <!-- v-if="scope.row.value == true ? true : false" -->
            <el-button
              class="green"
              size="mini"
              @click="handleEdit(scope.row.id)"
              ><i class="el-icon-edit"></i
            ></el-button>
            <el-button
              class="red"
              size="mini"
              @click="handleDelete(scope.row.id)"
              ><i class="el-icon-delete"></i
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current_page"
          :page-sizes="pageSizeArr"
          :page-size="pages.per_page"
          layout="total, sizes, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      class="tab"
      title="编辑"
      width="25%"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="editForm" ref="editForm">
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-input
            placeholder="请输入角色"
            v-model="editForm.title"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
          <el-tree
            ref="treelist"
            :data="PermissionList"
            node-key="id"
            show-checkbox
            :props="defaultProps"
            :default-checked-keys="deptKey"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editModify('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { leftmenus } from "../../api/jurisdiction/index";
import {
  newRole,
  roleList,
  roledel,
  rolesquery,
  changeRole,
  rolesModify,
} from "../../api/role/index";
import commonInfo from "@/utils/common";
export default {
  data() {
    return {
      //按钮显示隐藏
      xsyc: "1",

      /*   isShow: true, */

      //添加角色
      idList: [],
      /* 添加角色表单 */
      roleForm: {
        title: "",
        permissions: "",
      },
      /* 树状数据 */
      data: [
        {
          id: "",
          title: "",
          children: [],
        },
      ],

      rules: {
        title: [
          {
            required: true,
            message: "请输入公司名称",
            trigger: "blur",
          },
        ],
      },

      //编辑蒙尘

      dialogFormVisible: false,
      /* 编辑表单 */
      editForm: {
        title: "",
        permissions: "",
      },
      /* 默认勾选的数组 */
      deptKey: [],
      /*       deptParentKey: [], */
      formLabelWidth: "15%",
      //权限id
      permissionsId: [],
      /* 表格数据 */
      tableData: [],
      /* rolesForm: {
        input: "",
      }, */
      //分页
      pageSizeArr: JSON.parse(JSON.stringify(commonInfo.pageSizeArr)),

      pages: {
        per_page: 10,
        page: 1,
        keyword: "",
      },

      current_page: 1,

      total: 0,
      isLoading: true,
      /* 添加角色蒙尘 */
      drawerVisible: false,
      /* 添加角色权限树状图数据 */
      PermissionList: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
    };
  },
  methods: {
    async loadData(num) {
      let res = await roleList(num);
      console.log(res, "122");
      this.isLoading = false;
      if (res.data.code == 200) {
        this.tableData = res.data.data.data;
        this.current_page = res.data.current_page;

        this.total = res.data.total;
      }
      this.total = res.data.data.total;
      this.current_page = res.data.data.current_page;
    },
    INput() {
      if (this.pages.keyword == "") {
        this.loadData();
      }
    },
    /* 角色启用禁用 */
    async SwitchChange(row) {
      console.log(row);
      let id = row.id;
      let status = row.status;
      let res = await changeRole({ id, status });
      console.log(res);
      if (res.data.code === 200) {
        this.$message({
          showClose: true,
          duration: 3000,
          message: res.data.msg,
          type: "success",
        });
        this.loadData();
      } else {
        this.$message({
          showClose: true,
          duration: 3000,
          message: res.data.msg,
          type: "error",
        });
      }
    },
    //搜索
    async goSearch() {
      this.pages.page = 1;
      this.pages.per_page = 10;
      this.current_page = 1;
      console.log(this.pages);
      if (this.pages.keyword == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      }
      let res = await roleList(this.pages);
      console.log(res, "123");
      this.tableData = res.data.data.data;
      this.total = res.data.data.total;
      this.current_page = res.data.data.current_page;
    },

    //删除
    handleDelete(id) {
      this.$confirm("确认删除？")
        .then(async () => {
          let res = await roledel({ id });
          //console.log(res);
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "success",
            });
            this.loadData();
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "error",
            });
          }
        })
        .catch((_) => {});
    },
    //添加角色
    async Addrole() {
      let res = await leftmenus();
      this.drawerVisible = true;

      if (res.data.code == 200) {
        this.data = res.data.data;
        this.loadData();
      }
    },
    //显示和隐藏
    async gorolederails() {
      let res = await leftmenus();
      if (res.data.code == 200) {
        this.PermissionList = res.data.data;
      }
    },

    //编辑
    async handleEdit(id) {
      let res = await rolesquery({ id });
      console.log(res);
      this.editForm.title = res.data.data.title;
      this.editForm.id = res.data.data.id;
      this.editForm.permissions = res.data.data.rules;
      let arr = res.data.data.rules.map((i) => i.id);
      let arr2 = res.data.data.rules.map((i) => i.parent_id);
      let arr3 = [];
      arr.forEach((item) => {
        if (arr2.includes(item)) {
        } else {
          arr3.push(item);
        }
      });
      console.log(arr3);
      this.deptKey = arr3;
      this.gorolederails();
      this.dialogFormVisible = true;
    },
    //编辑成功
    editModify(formName) {
      //console.log(this.editForm);
      this.permissionsId = this.$refs.treelist.getCheckedNodes(false, true);
      this.editForm.permissions = this.permissionsId.map((i) => i.id).join(",");

      this.$refs[formName].validate(async (valid) => {
        //console.log(valid);
        if (valid) {
          let res = await rolesModify(this.editForm);
          //console.log(res);
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "success",
            });
            this.$refs[formName].resetFields();
            this.loadData();
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "error",
            });
          }
        }
        this.dialogFormVisible = false;
      });
    },
    //添加角色-提交
    getCheckedNodes(formName) {
      this.idList = this.$refs.tree.getCheckedNodes(false, true);
      let ids = this.idList.map((i) => i.id);
      this.roleForm.permissions = ids.join(",");
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //console.log("111");
          //console.log(this.roleForm);
          let res = await newRole(this.roleForm);
          //console.log(res);
          if (res.data.code == 200) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "success",
            });
            this.drawerVisible = false;
            this.$refs[formName].resetFields();
            this.loadData();
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "error",
            });
          }
        }
      });
    },
    //返回上一个页面
    /*   goPrevious() {
      this.isShow = true;
    }, */
    //分页
    handleCurrentChange(val) {
      this.current_page = val;
      this.pages.page = val;
      console.log(1);
      this.loadData(this.pages);
    },
    //分页
    handleSizeChange(val) {
      this.pages.per_page = val;
      console.log(2);
      this.loadData(this.pages);
    },
  },
  created() {
    this.loadData();
  },
};
</script>


<style scoped lang="less">
.common-main {
  background-color: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  margin: 15px 10px;
}
.drawerCenter {
  width: 80%;
  margin: 0 auto;
  padding-top: 50px;
}
.login-btn {
  margin-top: 30px;
  margin-left: 60px;
  display: flex;
  justify-content: space-around;
}
.login-btn button {
  width: 30%;
  height: 36px;
  margin-bottom: 10px;
}
/deep/.el-table__header {
  margin-bottom: 20px;
}
/deep/.el-table {
  background-color: #f3f5fb;
}
/deep/.el-table .cell {
  display: flex;
}
/deep/.el-button--mini {
  font-size: 18px !important;
  padding: 7px 5px;
}
</style>
